/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.service.impl;

import java.util.Properties;

import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.springframework.util.StringUtils;

import com.cqcis.uip.base.framework.service.EncryptorService;

/**
 * @author liuhz create 2008-9-22
 */
public class JasyptEncryptorService implements EncryptorService {
	public final static String UIP_JASYPT_PASSWORD = "uip.jasypt.password";
	public final static String UIP_JASYPT_PASSWORD_ENV = "uip.jasypt.password.env";

	private final static String JASYPT_PASSWORD = "cqpf";
	private final static String JASYPT_ALGORITHM = "PBEWithMD5AndDES";

	private StringEncryptor encryptor;

	public JasyptEncryptorService(Properties props) {
		this(props.getProperty(UIP_JASYPT_PASSWORD), props.getProperty(UIP_JASYPT_PASSWORD_ENV));
	}

	public JasyptEncryptorService(String password, String passwordEnv) {
		EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
		if (StringUtils.hasText(passwordEnv)) {
			config.setPasswordEnvName(passwordEnv);
		} else {
			config.setPassword(StringUtils.hasText(passwordEnv) ? password : JASYPT_PASSWORD);
		}

		config.setAlgorithm(JASYPT_ALGORITHM);

		encryptor = new StandardPBEStringEncryptor();
		((StandardPBEStringEncryptor) encryptor).setConfig(config);
	}

	/**
	 * @see com.cqcis.uip.base.framework.service.EncryptorService#encrypt(java.lang.String)
	 */
	public String encrypt(String encodedValue) {
		return PropertyValueEncryptionUtils.encrypt(encodedValue, this.encryptor);
	}

	/**
	 * @see com.cqcis.uip.base.framework.service.EncryptorService#edcrypt(java.lang.String)
	 */
	public String decrypt(String decodedValue) {
		return PropertyValueEncryptionUtils.decrypt(decodedValue, this.encryptor);
	}

	/**
	 * @see com.cqcis.uip.base.framework.service.EncryptorService#isEncryptedValue(java.lang.String)
	 */
	public boolean isEncryptedValue(String decodedValue) {
		return PropertyValueEncryptionUtils.isEncryptedValue(decodedValue);
	}

}
